package com.ruoyi.recyclecomprehensive.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.recycle.domain.MerchantManagement;
import com.ruoyi.recycle.dto.LoginDTO;
import com.ruoyi.recycle.exception.BusinessException;
import com.ruoyi.recycle.properties.Wxproperties;
import com.ruoyi.recycle.service.IMerchantManagementService;
import com.ruoyi.recycle.vo.LoginVO;
import com.ruoyi.recyclecomprehensive.service.LoginService;
import com.ruoyi.system.api.RemoteLoginService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.form.LoginBody;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RemoteLoginService remoteLoginService;
    @Autowired
    private RemoteUserService userService;
    @Autowired
    private IMerchantManagementService merchantManagementService;
    @Autowired
    private Wxproperties wxproperties;

    @Override
    @SuppressWarnings("unchecked")
    public LoginVO login(LoginDTO loginDTO) throws Exception {
        final MerchantManagement merchantManagement = new MerchantManagement();
        MerchantManagement account = merchantManagementService.getOne(Wrappers.lambdaQuery(merchantManagement)
                .eq(MerchantManagement::getMerchantNumber, loginDTO.getUsername()));
        if (Objects.isNull(account)) {
            throw new Exception("找不到该账号");
        }
        if (!StrUtil.equals(account.getStatus(), "1")) {
            throw new BusinessException("账号未被启用,请联系管理人员");
        }
        if (StrUtil.isEmpty(account.getOpenid()) && StrUtil.isEmpty(loginDTO.getOpenId())) {
            throw new BusinessException("无法获取用户openId,请先进行微信授权,以获取用户微信信息");
        }
        if (StrUtil.isNotEmpty(loginDTO.getOpenId()) && StrUtil.isEmpty(account.getOpenid())) {
            account.setOpenid(loginDTO.getOpenId());
            merchantManagementService.updateById(account);
        }
        final R<?> login = remoteLoginService.login(new LoginBody()
                .setUsername(loginDTO.getUsername())
                .setPassword(loginDTO.getPassword())
                .setIsProgram(true));
        final Map<String, Object> data = (Map<String, Object>) login.getData();
        final R<LoginUser> userInfo = userService.getUserInfo(loginDTO.getUsername(), SecurityConstants.INNER);
        return new LoginVO().setMerchantInfo(account)
                .setUserInfo((userInfo.getData()))
                .setToken(data.get("access_token"))
                .setExpireTime(data.get("expires_in"));
    }

    @Override
    public Map<String, String> wechatAuth(String code, String encryptedData, String iv) {
        Map<String, String> authMap = new HashMap<>(2);
        final String authUrl = StrUtil.indexedFormat(wxproperties.getAuthUrl(), wxproperties.getComprehensiveAppId(), wxproperties.getComprehensiveAppSecretKey(), code);
        String result = HttpUtil.get(authUrl);
        final JSONObject jsonObject = JSONObject.parseObject(result);
        authMap.put("errmsg", jsonObject.getString("errmsg"));
        authMap.put("openId", jsonObject.getString("openid"));
        return authMap;

    }

    @Override
    public R logout(HttpServletRequest request) {
        try {
            return remoteLoginService.logout(request);
        } catch (Exception e) {
            log.error("引流门店用户登出操作产生错误,原因:{}", e.getMessage());
            return R.fail();
        }
    }


}
